import 'package:dio/dio.dart';
import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_module_sale/config/route/native_route.dart';

class CommonHttpClient extends BaseHttpClient with ClientMixIn {
  // 工厂模式
  factory CommonHttpClient() => _getInstance();

  static CommonHttpClient get instance => _getInstance();
  static CommonHttpClient _instance;

  CommonHttpClient._internal();

  static CommonHttpClient _getInstance() {
    if (_instance == null) {
      _instance = CommonHttpClient._internal();
    }
    return _instance;
  }

  @override
  BaseOptions get netOptions {
    return BaseOptions(
        connectTimeout: Env.value?.netWorkConfig?.connectTimeout ?? 15000,
        receiveTimeout: Env.value?.netWorkConfig?.receiveTimeout ?? 15000);
  }

  static const String INVALID_TOKEN_SALE = "10000001"; // 销售的过期token
  static const String INVALID_TOKEN_SALE_OLD = "-10001"; // 销售的过期token
  static const String INVALID_TOKEN_PORTAL = "2050403"; // 门户的过期token
  @override
  bool handleErrorCode(String code) {
    if (stringBlank(code)) {
      return true;
    }
    bool isHandleNext = true;
    switch (code) {
      case INVALID_TOKEN_PORTAL:
      case INVALID_TOKEN_SALE:
      case INVALID_TOKEN_SALE_OLD:
        RouteUtil.goPage(NativeRoute.LOGIN);
        isHandleNext = false;
        break;
    }
    return isHandleNext;
  }

  ///默认添加[DefaultRequestInterceptor]拦截器
  @override
  void addInterceptor(Interceptors interceptors) {
    interceptors.add(DefaultRequestInterceptor());
    interceptors.add(HeaderInterceptor());
  }
}

class HeaderInterceptor extends Interceptor {
  @override
  FutureOr<dynamic> onRequest(RequestOptions options) {
    if (null != options && null != options.headers) {
      options.headers["X-Source"] = "app";
    }
  }
}
